#!/user/bin/env python
# -*- coding: UTF-8 -*-
# Author: xieyuheng
# Date: 2024/2/26
"""
该文件用于 所有页面的公共方法的集合
"""
import re
import os
import time
import math
import uiautomation as auto
import pyautogui
import constant
from page.browser import Browser
from utils.utils_operation import get_current_time
from utils.utils_log import loggerCase
from common.soft_operate import close_app_kill

file = constant.ui_log_image_path + os.sep + get_current_time(format="%Y_%m_%d_%H_%M_%S")
os.mkdir(file)


class BasePage:
    """基本页面类"""
    pyautogui.PAUSE = 0.2

    def __init__(self):
        self.driver = Browser().driver

        # 进度条
        self.__waiting = self.driver.GroupControl(SubName="access_waiting")

    __waring_text = auto.TextControl(SubName="Warning")

    __notice_text = auto.TextControl(SubName="Notice")

    __apply_button = auto.ButtonControl(SubName="Apply")

    __confirm_group = auto.GroupControl(SubName="Confirm")

    __confirm_button = auto.ButtonControl(SubName="Confirm")

    __continue_button = auto.ButtonControl(SubName="Continue")

    __exit_button = auto.ButtonControl(SubName="Exit")

    __next_button = auto.ButtonControl(SubName="Next")

    __yes_button = auto.ButtonControl(SubName="Yes")

    __no_button = auto.ButtonControl(SubName="No")

    __cancel_button = auto.ButtonControl(SubName="Cancel")

    __clear_all_button = auto.ButtonControl(SubName="Clear all")

    # 新建工程
    __new_project_button = auto.ButtonControl(Name="New project group")

    # 导入工程
    __open_project_group = auto.ButtonControl(Name="Open project group")

    # 判断是否有警告弹框
    def is_has_notice(self, text, max_wait_time=3):
        """
        判断是否有提示弹框
        :param text: 警告弹框的文本内容
        :return:
        """
        loggerCase.info("判断是否出现提示框")
        res = self.judge_element_exist(self.__notice_text, is_need_screen=False, is_end=False,
                                       max_wait_time=max_wait_time,
                                       max_retries=1) or \
              self.judge_element_exist(self.__waring_text, is_need_screen=False, is_end=False,
                                       max_wait_time=max_wait_time,
                                       max_retries=1)
        if res:
            loggerCase.info(text)
        return res

    def is_has_apply_button(self):
        """
        是否存在应用按钮
        :return:
        """
        loggerCase.info("是否存在应用按钮")
        return self.judge_element_exist(self.__apply_button, max_wait_time=3, max_retries=1,
                                        is_end=False,
                                        is_need_screen=False)

    def is_has_confirm_button(self):
        """
        是否存在确认按钮
        :return:
        """
        loggerCase.info("是否存在确认按钮")
        return self.judge_element_exist(self.__confirm_button, max_wait_time=3, max_retries=1,
                                        is_end=False,
                                        is_need_screen=False)

    def is_has_confirm_group(self):
        """
        是否存在确认按钮
        :return:
        """
        loggerCase.info("是否存在确认按钮")
        return self.judge_element_exist(self.__confirm_group, is_need_screen=False, is_end=False,
                                        max_wait_time=3,
                                        max_retries=1)

    def is_has_exit_button(self):
        """
        是否存在退出按钮
        :return:
        """
        loggerCase.info("是否存在退出按钮")
        return self.judge_element_exist(self.__exit_button, max_wait_time=3, max_retries=1,
                                        is_end=False,
                                        is_need_screen=False)

    def is_has_next_button(self):
        """
        是否有下一步按钮
        """
        loggerCase.info("判断是否有下一步")
        return self.judge_element_exist(self.__next_button, max_wait_time=3, max_retries=1,
                                        is_need_screen=False, is_end=False)

    def click_confirm_button(self, max_wait_time=3):
        """
        点击确认按钮
        :return:
        """
        loggerCase.info("点击确认按钮")
        self.click(self.__confirm_button, max_wait_time=max_wait_time)
        self.loading()
        # if self.is_has_confirm_button():
        #     self.click(self.__confirm_button, max_wait_time=max_wait_time)
        # elif self.is_has_confirm_group():
        #     self.click(self.__confirm_group,max_wait_time=max_wait_time)
        # else:
        #     loggerCase.error("未找到确认按钮")

    def click_yes_button(self, max_wait_time=3):
        """
        点击yes按钮
        :return:
        """
        loggerCase.info("点击yes按钮")
        self.click(self.__yes_button, max_wait_time=max_wait_time)
        self.loading()

    def click_continue_button(self, max_wait_time=3):
        """
        continue
        :return:
        """
        loggerCase.info("点击continue按钮")
        self.click(self.__continue_button, max_wait_time=max_wait_time)
        self.loading()

    def click_no_button(self, max_wait_time=3):
        """
        点击no按钮
        :return:
        """
        loggerCase.info("点击no按钮")
        self.click(self.__no_button, max_wait_time=max_wait_time)

    def click_apply_button(self, max_wait_time=3):
        """
        点击应用按钮
        :return:
        """
        loggerCase.info("点击应用按钮")
        self.click(self.__apply_button, max_wait_time=max_wait_time)
        self.loading()

    def click_next_button(self, max_wait_time=3):
        """
        点击下一步按钮
        :return:
        """
        loggerCase.info("点击下一步按钮")
        self.click(self.__next_button, max_wait_time=max_wait_time)

    def click_exit_button(self, max_wait_time=3):
        """
        点击退出按钮
        :return:
        """
        loggerCase.info("点击退出按钮")
        self.click(self.__exit_button, max_wait_time=max_wait_time)

    def click_cancel_button(self, max_wait_time=5):
        """
        点击取消按钮
        :return:
        """
        loggerCase.info("点击取消按钮")
        self.click(self.__cancel_button, max_wait_time=max_wait_time)

    def click_clear_all_button(self, max_wait_time=3):
        """
        点击clearall按钮
        :return:
        """
        loggerCase.info("点击清空按钮")
        self.click(self.__clear_all_button, max_wait_time=max_wait_time)

    def click_new_project_button(self, max_wait_time=3):
        """新建工程"""
        loggerCase.info("点击新建工程")
        self.click(self.__new_project_button, max_wait_time=max_wait_time)

    def click_open_project_button(self, max_wait_time=3):
        """打开工程"""
        loggerCase.info("点击打开工程")
        self.click(self.__open_project_group, max_wait_time=max_wait_time)

    def loading(self, wait_time=1):
        """
        加载进度条
        :param wait_time:
        :return:
        """
        loggerCase.debug("加载进度条")
        while self.judge_element_exist(element=self.__waiting, max_wait_time=1,
                                       is_need_screen=False, is_end=False, max_retries=1):
            time.sleep(wait_time)
        loggerCase.debug("加载完成")

    def wait_time(self, wait_time):
        """
        进行等待
        :param wait_time: 等待时间
        :return:
        """
        loggerCase.debug("开始等待")
        _wait_time = int(wait_time)
        time.sleep(_wait_time)
        loggerCase.debug("开始结束")

    def close(self):
        """
        关闭软件
        :return:
        """
        close_app_kill()
        Browser.driver = None

    def add_screen(self, text=time.strftime("%Y%m%d%H%M%S")):
        """
        截图
        :param text: 截图的名字
        :return:
        """
        # 截图放在项目中
        picture_path = constant.picture_path + "\\" + text + ".png"
        pyautogui.screenshot().save(picture_path)
        loggerCase.debug(f"截图到 -> {picture_path}")

    def add_screen_platform(self):
        """
        截图放在static中
        :param text:
        :return:
        """
        text = str(
            time.strftime(f"%Y_%m_%d_%H_%M_%S", time.localtime(
                time.time())))
        file_path = file + os.sep + text + '.png'
        pyautogui.screenshot().save(file_path)
        return os.path.relpath(file_path, constant.test_report_ui_path)

    # ===========================auto操作==================================================================
    def judge_element_exist(self, element, max_wait_time=1, is_need_screen=True, is_end=True, max_retries=3):
        """
        element:元素
        max_wait_time：最大等待时间
        is_need_screen： 是否需要截图
        """
        count = 0
        while count < max_retries:
            if element.Exists(maxSearchSeconds=max_wait_time):
                return True
            else:
                count += 1
                time.sleep(0.5)
        if is_need_screen:
            self.add_screen()
        if is_end:
            loggerCase.error("元素不存在", extra={"image_path": self.add_screen_platform()})
            raise Exception("元素不存在异常")
            # sys.exit()
        else:
            return False

    def click(self, element, times=1, max_wait_time=1, is_need_judge=True):
        """
        最大等待时间：遇到有进度条时，需要用到
        element:元素
        times：点击次数
        max_wait_time：最大等待时间
        is_need_screen： 是否需要截图
        """
        if is_need_judge:
            if self.judge_element_exist(element, max_wait_time=max_wait_time):
                for i in range(times):
                    element.Click()
        else:
            for i in range(times):
                element.Click()

    def double_click(self, element, times=1, max_wait_time=1, is_need_judge=True):
        """
        最大等待时间：遇到有进度条时，需要用到
        element:元素
        times：点击次数
        max_wait_time：最大等待时间
        is_need_screen： 是否需要截图
        """
        if is_need_judge:
            if self.judge_element_exist(element, max_wait_time=max_wait_time):
                for i in range(times):
                    element.DoubleClick()
        else:
            for i in range(times):
                element.DoubleClick()

    def send_key(self, element, text):
        """
        输入内容
        :param element: 元素
        :param text: 需要输入的文本
        :return:
        """
        if self.judge_element_exist(element):
            element.SetFocus()
            auto.SendKeys("{Ctrl}a")
            element.SendKeys(text)
            time.sleep(0.5)
            self.ENTER()

    def set_resolution(self, spinner_element, slider_element, middle_value, final_value):
        """
        spinner_element: 输入框
        slider_element: 滑动条
        通过分辨路的中间值来改变：需要提前知道中间中是多少
        """
        loggerCase.info("点距设置为:" + str(final_value))
        if self.judge_element_exist(slider_element) and isinstance(spinner_element, auto.SpinnerControl):
            final_value = math.floor(final_value * 10) / 10
            x, y = slider_element.GetPosition()
            auto.Click(x=x, y=y)
            spinner_element.SetFocus()
            if final_value > middle_value:
                for i in range(0, int((final_value - middle_value) * 10) + 1):
                    self.press_key(auto.Keys.VK_UP, wait_time=0.2)
            if final_value < middle_value:
                for i in range(1, int((middle_value - final_value) * 10) + 1):
                    self.press_key(auto.Keys.VK_DOWN, wait_time=0.2)

    def click_slider(self, slider_element, max_wait_time=1):
        """
        点击滑动条
        """
        if self.judge_element_exist(slider_element, max_wait_time=max_wait_time) and isinstance(slider_element,
                                                                                                auto.SliderControl):
            x, y = slider_element.GetPosition()
            auto.Click(x=x, y=y)

    def press_key(self, text, wait_time=1.0):
        """
        按下按钮
        """
        loggerCase.info("使用auto按下键盘")
        auto.PressKey(text, waitTime=wait_time)

    def judge_element_is_Enabled(self, element):
        """
        判断控件是否可用
        """
        if re.search(pattern="Enabled", string=element.Name, flags=re.I) is not None:
            if re.findall("Enabled_(.+?)_", element.Name):
                return re.findall("Enabled_(.+?)_", element.Name)[0] == "true"
            elif re.findall("Enabled_(.+)", element.Name):
                return re.findall("Enabled_(.+)", element.Name)[0] == "true"
        return False

    def judge_element_is_Checked(self, element):
        """
        判断控件是否被选中
        """
        if re.search(pattern="Checked", string=element.Name, flags=re.I) is not None:
            if re.findall("Checked_(.+?)_", element.Name):
                return re.findall("Checked_(.+?)_", element.Name)[0] == "true"
            elif re.findall("Checked_(.+)", element.Name):
                return re.findall("Checked_(.+)", element.Name)[0] == "true"
        return False

    def ENTER(self):
        """回车"""
        pyautogui.press("enter")
